package com.example.easyexcel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.easyexcel.dao.AssetTargetInfoMapper;
import com.example.easyexcel.dto.AssetTargetInfo;
import lombok.extern.slf4j.Slf4j;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

@Slf4j
public class AssetTargetInfoListener extends AnalysisEventListener<AssetTargetInfo> {
    private final AssetTargetInfoMapper mapper;
    private final List<AssetTargetInfo> batchList = new ArrayList<>();
    private final AtomicInteger processedCount = new AtomicInteger(0);
    private final AtomicInteger failedCount = new AtomicInteger(0);
    private final int BATCH_SIZE = 10000;

    // 每个监听器实例有自己的计数器，根据Sheet编号分配起始值
    private final AtomicLong sheetAssetNoCounter;
    private final long sheetStartIndex;
    private final int sheetIndex;

    /**
     * 修改构造函数，接收Sheet编号和起始索引
     */
    public AssetTargetInfoListener(AssetTargetInfoMapper mapper, int sheetIndex, long startIndex) {
        this.mapper = mapper;
        this.sheetIndex = sheetIndex;
        this.sheetStartIndex = startIndex;
        this.sheetAssetNoCounter = new AtomicLong(startIndex);

        log.info("Sheet[{}] 监听器创建，asset_no起始值: {}", sheetIndex, startIndex);
    }

    @Override
    public void invoke(AssetTargetInfo data, AnalysisContext context) {
        try {
            // 同步整个转换和添加过程
            synchronized (batchList) {
                AssetTargetInfo entity = convertToEntity(data);
                batchList.add(entity);
                if (batchList.size() >= BATCH_SIZE) {
                    saveBatchData();
                }
            }
            processedCount.incrementAndGet();
        } catch (Exception e) {
            failedCount.incrementAndGet();
            int rowIndex = context.readRowHolder().getRowIndex() + 1;
            log.error("Sheet[{}] 第{}行数据转换失败: {}", sheetIndex, rowIndex, e.getMessage());
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 处理最后一批数据
        synchronized (batchList) {
            if (!batchList.isEmpty()) {
                saveBatchData();
            }
        }
        log.info("Sheet[{}] 解析完成: 成功处理 {} 条, 失败 {} 条, asset_no范围: {} - {}",
                sheetIndex, processedCount.get(), failedCount.get(),
                getStartAssetNo(), getEndAssetNo());
    }

    /**
     * 批量保存数据
     */
    private void saveBatchData() {
        List<AssetTargetInfo> currentBatch;
        synchronized (batchList) {
            currentBatch = new ArrayList<>(batchList);
            batchList.clear();
        }

        if (currentBatch.isEmpty()) {
            return;
        }

        try {
            // 为当前批次生成连续的编号
            long start = sheetAssetNoCounter.getAndAdd(currentBatch.size());
            for (int i = 0; i < currentBatch.size(); i++) {
                AssetTargetInfo entity = currentBatch.get(i);
                String assetNo = "MT" + String.format("%09d", start + i);
                entity.setAssetNo(assetNo);
            }

            int insertedCount = mapper.insertBatch(currentBatch);
            log.debug("Sheet[{}] 批量插入 {} 条数据, 成功 {} 条, asset_no范围: {} - {}",
                    sheetIndex, currentBatch.size(), insertedCount,
                    formatAssetNo(start), formatAssetNo(start + currentBatch.size() - 1));
        } catch (Exception e) {
            failedCount.addAndGet(currentBatch.size());
            log.error("Sheet[{}] 批量插入失败: {}", sheetIndex, e.getMessage());
        }
    }

    /**
     * 数据转换方法（不再生成assetNo，移至批量保存时处理）
     */
    private AssetTargetInfo convertToEntity(AssetTargetInfo dto) {
        AssetTargetInfo entity = new AssetTargetInfo();

        // 基础字段映射
        entity.setTargetName(dto.getTargetName());
        entity.setTargetDefinition(dto.getTargetDefinition());
        entity.setTargetStatsCoverage(dto.getTargetStatsCoverage());
        entity.setCntOrg(dto.getCntOrg());

        // 转换指标类型代码
        entity.setTargetTc(convertTargetTc(dto.getTargetType()));

        // 计算时间维度类型代码
        entity.setTimeDimensionTc(calculateTimeDimensionTc(dto));

        // 设置系统字段
        LocalDateTime now = LocalDateTime.now();
        entity.setCreateTime(now);
        entity.setUpdateTime(now);
        entity.setDelFlag(0L);
        entity.setDelTime(null);

        return entity;
    }

    /**
     * 获取当前Sheet的起始asset_no
     */
    private String getStartAssetNo() {
        return formatAssetNo(sheetStartIndex);
    }

    /**
     * 获取当前Sheet的结束asset_no
     */
    private String getEndAssetNo() {
        long endIndex = sheetStartIndex + processedCount.get() - 1;
        return formatAssetNo(endIndex);
    }

    /**
     * 格式化asset_no
     */
    private String formatAssetNo(long number) {
        return "MT" + String.format("%09d", number);
    }

    private Integer convertTargetTc(String targetType) {
        if (targetType == null) return null;
        if (targetType.contains("基础指标")) return 0;
        if (targetType.contains("组合指标")) return 1;
        return null;
    }

    private Integer calculateTimeDimensionTc(AssetTargetInfo dto) {
        boolean hasCalendarYear = dto.getCalendarYear() != null &&
                !dto.getCalendarYear().trim().isEmpty();
        boolean hasLotteryYear = dto.getLotteryYear() != null &&
                !dto.getLotteryYear().trim().isEmpty();

        if (hasCalendarYear && hasLotteryYear) return 2;
        if (hasCalendarYear) return 0;
        if (hasLotteryYear) return 1;
        return null;
    }
}